package com.aop.demo.test;

import com.aop.demo.mapper.UserMapper;
import com.aop.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class UserService {

    @Autowired
    protected UserMapper userMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    public void test(User user, boolean flag) throws Exception {
        UserService bean = applicationContext.getBean(UserService.class);
        bean.save(user, flag);
        save(user, flag);
    }

    @Transactional(rollbackFor = Throwable.class)
    public void save(User user, boolean flag) {
        /*try {
            userMapper.insertSelective(user);
            if (flag) {
                throw new Exception();
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }*/

        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction = transactionManager.getTransaction(definition);
        try {
            userMapper.insertSelective(user);
            if (flag) {
                throw new Exception();
            }
            transactionManager.commit(transaction);
        } catch (Exception e) {
            transactionManager.rollback(transaction);
        }
    }
}
